<template>
    <div class="permission-container">
        <!-- 统计卡片 -->
        <PermissionStats
            :total-permissions="totalPermissions"
            :enabled-permissions="enabledPermissions"
            :disabled-permissions="disabledPermissions"
            :admin-permissions="adminPermissions"
        />

        <!-- 工具栏 -->
        <PermissionToolbar
            :loading="loading"
            @refresh="handleRefresh"
            @add="handleAdd"
            @is-spread="isSpread = !isSpread"
        />
        <!-- 内容区域 -->
        <div class="permission-container__content rounded-2xl overflow-hidden transition-all duration-200">
            <!-- 权限表格 -->
            <PermissionTable
                :isSpread="isSpread"
                :data-source="convertPermissions"
                :loading="loading"
                @edit="handleEdit"
                @add="handleAdd"
                @delete="handleDelete"
            />
        </div>

        <!-- 权限编辑模态框 -->
        <!-- <PermissionModal
            v-model:open="modalVisible"
            :data="currentPermission"
            :loading="modalLoading"
            @ok="handleModalOk"
            @cancel="handleModalCancel"
        /> -->
        <PermissionFormDrawer
            v-model:open="isOpenDrawer"
            :title="DeawerTitle"
            :loading="drawerLoading"
            :model-value="formData"
            :tree-data="convertPermissions"
            @submit="onDrawerSubmit"
        />
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
    AddSysPermissionApi,
    UpdateSysPermissionApi,
    getPermissionListApi,
    DeleteSysPermissionApi,
    type PermissionNode,
    type SysPermissions,
} from '@/api/core/prmissions'
import { PermissionStats, PermissionTable, PermissionToolbar, PermissionFormDrawer } from './components'

// 响应式数据
const permissions = ref<SysPermissions[]>([])
const convertPermissions = ref<PermissionNode[]>([])
const loading = ref(false)
const currentPermission = ref<SysPermissions | null>(null)
const deleteTarget = ref<SysPermissions | null>(null)
const isSpread = ref<boolean>(false)

// 抽屉响应式数据
const isOpenDrawer = ref<boolean>(false)
const DeawerTitle = ref<string>('新增菜单')
const drawerLoading = ref<boolean>(false)

// 表单数据（由子组件消费）
const formData = ref<Partial<SysPermissions>>({
    permissionName: '',
    routeTitle: '',
    routeName: '',
    routePath: '',
    componentPath: '',
    icon: '',
    activeRoute: '',
    parentId: 0,
    sortOrder: 0,
    permissionLevel: 0,
    isHidden: 0,
    status: 1,
    description: '',
})

// 校验与显示逻辑交由子组件处理

// 统计计算
const totalPermissions = computed(() => permissions.value.length)
const enabledPermissions = computed(() => permissions.value.filter((p) => p.status === 1).length)
const disabledPermissions = computed(() => permissions.value.filter((p) => p.status === 0).length)
const adminPermissions = computed(() => permissions.value.filter((p) => p.permissionLevel <= 2).length)

// 获取权限列表
const fetchPermissions = async () => {
    loading.value = true
    getPermissionListApi()
        .then((res) => {
            permissions.value = res.data
            convertPermissions.value = convertPermission(res.data || [])
        })
        .finally(() => {
            loading.value = false
        })
}

const convertPermission = (permissions: SysPermissions[] | []) => {
    const levelOneRutes = permissions.filter((item): boolean => item.parentId === 0)
    const grouped: Record<number, PermissionNode[]> = {}

    permissions.forEach((item) => {
        if (item.parentId !== 0) {
            if (!grouped[item.parentId]) {
                grouped[item.parentId] = []
            }
            grouped[item.parentId].push(item)
        }
    })

    const attachChildrenRecursively = (node: PermissionNode) => {
        const children = grouped[node.id] || []
        if (children.length > 0) {
            node.children = children
            children.forEach((child) => attachChildrenRecursively(child))
        } else {
            // 当没有子节点时，移除 children 字段，避免产生空 children
            Reflect.deleteProperty(node as object, 'children')
        }
    }

    levelOneRutes.forEach((item) => {
        attachChildrenRecursively(item)
    })
    return levelOneRutes
}

// 处理刷新
const handleRefresh = () => {
    // 清空数据
    permissions.value = []

    fetchPermissions()
}

// 处理新增
const resetForm = () => {
    formData.value = {
        permissionName: '',
        routeTitle: '',
        routeName: '',
        routePath: '',
        componentPath: '',
        icon: '',
        activeRoute: '',
        parentId: 0,
        sortOrder: 0,
        permissionLevel: 0,
        isHidden: 0,
        status: 1,
        description: '',
    }
    // 重置由父级直接控制初始值
}

const handleAdd = (record?: SysPermissions) => {
    isOpenDrawer.value = true
    DeawerTitle.value = '新增菜单'
    currentPermission.value = null
    if (record) {
        // 从当前行传入目录与权限相关参数，作为新增默认值
        formData.value = {
            permissionName: '',
            routeTitle: '',
            routeName: '',
            routePath: '',
            componentPath: '',
            icon: '',
            activeRoute: '',
            parentId: record.id, // 目录：默认挂载到当前行
            sortOrder: 0,
            permissionLevel: record.permissionLevel + 1, // 权限级别：默认沿用当前行（可在表单中修改）
            isHidden: record.isHidden,
            status: record.status,
            description: '',
        }
    } else {
        resetForm()
    }
}

// 处理编辑
const handleEdit = (record?: SysPermissions) => {
    isOpenDrawer.value = true
    DeawerTitle.value = '编辑菜单'
    if (record) {
        currentPermission.value = record
        formData.value = {
            id: record.id,
            permissionName: record.permissionName,
            routeTitle: record.routeTitle,
            routeName: record.routeName,
            routePath: record.routePath,
            componentPath: record.componentPath,
            icon: record.icon,
            activeRoute: record.activeRoute,
            parentId: record.parentId,
            sortOrder: record.sortOrder,
            permissionLevel: record.permissionLevel,
            isHidden: record.isHidden,
            status: record.status,
            description: record.description,
        }
        // 子组件接受并回填
    }
}

// 处理删除
const handleDelete = (record: SysPermissions) => {
    deleteTarget.value = record
    Modal.confirm({
        centered: true,
        title: '系统提示',
        content: `是否确认删除名称为「${record.routeTitle || record.permissionName || record.id}」的数据项？`,
        okText: '确认',
        cancelText: '取消',
        async onOk() {
            try {
                loading.value = true
                await DeleteSysPermissionApi(record.id)
                message.success('删除成功')
                await fetchPermissions()
            } catch (error) {
                const errorMsg = (error as { message?: string }).message || '删除失败'
                message.error(errorMsg)
            } finally {
                loading.value = false
            }
        },
    })
}

// 处理模态框确定
const handleModalOk = async (data: Partial<SysPermissions>) => {
    try {
        drawerLoading.value = true
        const isUpdate = Boolean(data.id)
        if (isUpdate) {
            await UpdateSysPermissionApi(data.id as number, data)
        } else {
            await AddSysPermissionApi(data)
        }
        message.success(isUpdate ? '权限更新成功' : '权限创建成功')
        isOpenDrawer.value = false
        await fetchPermissions()
    } catch (error) {
        const errorMsg = (error as { message?: string }).message
        message.error(errorMsg)
    } finally {
        drawerLoading.value = false
    }
}

// 子组件提交回调
const onDrawerSubmit = async (payload: Partial<SysPermissions>) => {
    await handleModalOk(payload)
}

// 组件挂载时获取数据
onMounted(() => {
    fetchPermissions()
})
</script>

<style lang="scss" scoped>
@use './style/index.scss';
</style>
